from datasource import *
import threading
import urllib2

class StockQuotationSinaImpl(StockQuotation):
	def __init__(self,str_data,scode):
		self._parse(str_data)
		self.code=scode
		
	def _parse(self,str_data):
		s=str_data.find('="')
		s=s+2
		e=str_data.rfind('"')
		ss=str_data[s:e]
		data_list=ss.split(',')
		data_list[0]=data_list[0].decode('gbk')
		self._parse_data(data_list)
		
	def _parse_data(self,data_list):
		self.name=data_list[0]
		self.price_today_start=float(data_list[1])
		self.price_lastday=float(data_list[2])
		self.price_now=float(data_list[3])
		self.price_highest=float(data_list[4])
		self.price_lowest=float(data_list[5])
		self.price_bid_buy=float(data_list[6])
		self.price_bid_sale=float(data_list[7])
		self.amount=float(data_list[8])
		self.amount_money=float(data_list[9])
		self.change=self.price_now-self.price_lastday
		if(self.price_lastday>0):self.change_percent=(self.change/self.price_lastday)*100.0
		else:self.change_percent=0.0
		self.date=data_list[30]
		self.time=data_list[31]
		self.slot_buy=[]
		self.slot_sale=[]
		for i in range(0,5):
			self.slot_buy.append((float(data_list[11+i*2]),float(data_list[10+i*2])))
			self.slot_sale.append((float(data_list[21+i*2]),float(data_list[20+i*2])))
			
			
class DataSourceSinaImpl(DataSource):
	def get_stock_quotation(self,stock_code_list,func=None,user_data=None):
		if(func==None):
			return self._get_stock_quotation(stock_code_list)
		else:
			threading.Thread(None,self._get_stock_quotation,(stock_code_list,func,user_data,))
			th.start()
			
	def _get_stock_quotation(self,stock_code_list,func=None,user_data=None):
		max_items=150
		sdl=[]
		lock=threading.Lock()
		j=len(stock_code_list)/max_items
		x=len(stock_code_list)%max_items
		if(x>0 and j==0):return self._get_stock_quotation_single(0,stock_code_list,sdl,lock)
		if(x>0):j=j+1
		thread_list=[]
		for i in range(0,j):
			p=stock_code_list[i*max_items:(i+1)*max_items]
			th=threading.Thread(None,self._get_stock_quotation_single,"p_download_data_%d" % i,(i,p,sdl,lock,))
			thread_list.append(th)
			th.start()
		for t in thread_list:
			t.join()
		if(func==None):return sdl
		else:func(sdl,*user_data)
		
	def _get_stock_quotation_single(self,index,stockids,sdl,lock):
		hq_url = "http://hq.sinajs.cn/list=%s"
		stockstr=','.join(stockids)
		url=hq_url % stockstr
		handle = urllib2.urlopen(url)
		buf = handle.read()
		listStr=buf.split(';')
		i=0
		rlist=[]
		while i<len(listStr)-1:
			str_data=listStr[i]
			if(len(str_data)<30):
				#print "error data : %s" % str_data
				i=i+1
				continue
			try:
				sd=StockQuotationSinaImpl(str_data,stockids[i])
				rlist.append(sd)
			except:
				print "error:%d:%s" % (i,str_data)
				pass #continue
			i=i+1
		lock.acquire()
		for x in rlist:sdl.append(x)
		#print "merge %d -> %d" % (index,len(sdl))
		lock.release()
		return sdl
		
	def get_img_to_file(self,stock_code,img_type,path,func=None,user_data=None):
		url = "http://image.sinajs.cn/newchart/%s/n/%s.gif" % (img_type,stock_code)
		self._get_url_to_file(url,path,func,user_data)
		
	def _get_url_to_file(self,url,path,func,user_data):
		if(func==None):
			self._download_img_1(path,url)
		else:
			th=threading.Thread(None,self._nonblock_get_img,"p_download_img",(url,path,func,user_data,))
			th.start()
		return path
		
	def _nonblock_get_img(self,url,path,func,data):
		self._download_img_1(path,url)
		func(path,*data)

	def _download_img_1(self,path,url):
		print url
		h=urllib2.urlopen(url)
		data=h.read()
		fo=open(path,"w")
		fo.write(data)
		fo.close()
    
	def _download_img_2(self,path,url):
		cmd="wget -q -O %s %s" % (path, url)
		print cmd
		os.system(cmd)
